//
//  VideosViewController.m
//  Corner
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 Zero_Zhou. All rights reserved.
//

#import "VideosViewController.h"
#import "NetworkTool.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import "VideoCollectionCell.h"
#import "VideoModel.h"
#import "WaterflowLayout.h"
#import <MJRefreshHeader.h>
#import "VideoDetailController.h"

@interface VideosViewController ()<UICollectionViewDataSource,WaterflowLayoutDelegate,UICollectionViewDelegate>
@property (nonatomic,strong)NSMutableArray *sourcrArray;
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)NSMutableArray *channelArr;

@property(nonatomic,assign) int i;
@property(nonatomic,strong)NSString *totalNumber;

@end

@implementation VideosViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.i = 3;
    
    self.sourcrArray = [[NSMutableArray alloc] init];
    self.channelArr = [[NSMutableArray alloc] init];
    self.title = @"视听";
    self.view.backgroundColor = [UIColor blueColor];
    // Do any additional setup after loading the view.
    //创建布局类
    WaterflowLayout *wFlowLayout = [[WaterflowLayout alloc] init];
    wFlowLayout.delegate = self;
//    wFlowLayout.columnMargin = 10;
    //创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:wFlowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    //设置dataSource delegate
    
    self.collectionView.dataSource =self;
    self.collectionView.delegate = self;
    //注册cell
    [self.collectionView registerClass:[VideoCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    //[self.collectionView.mj_header beginRefreshing];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.collectionView.mj_header endRefreshing];
    }];
    [self loadData];
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [self.collectionView.mj_header beginRefreshing];

}
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)loadData{
    NSString *url = [NSString stringWithFormat:@"http://api.miaopai.com/m/cate2_channel?cateid=67&extend=1&os=ios&page=2&per=20"];
    [self loadDataForType:1 withUrl:url];
}

- (void)loadMoreData{
    
    NSString *url = [NSString stringWithFormat:@"http://api.miaopai.com/m/cate2_channel?cateid=67&extend=1&os=ios&page=%d&per=20",self.i];
    self.i++;
    NSInteger temp = [self.totalNumber integerValue];
    if (self.i >= temp / 20 - 2) {
        return;
    }
    [self loadDataForType:2 withUrl:url];
}


//公共方法
- (void)loadDataForType:(int)type withUrl:(NSString *)allUrlString{
    /*
    [AFNetworkingTools jsonDataWithUrl:allUrlString success:^(id json) {
        NSArray *resultArr = json[@"result"];
        NSMutableArray *arrayM = [VideoModel mj_objectArrayWithKeyValuesArray:resultArr];
        if (type == 1) {
            self.sourcrArray = arrayM;
        }else if (type == 2){
            [self.sourcrArray addObjectsFromArray:arrayM];
        }
    } fail:^{
        NSLog(@"请求失败");
    }];
    */
    
    __weak VideosViewController *s = self;
    
    [[[NetworkTool sharedNetworkTools]GET:allUrlString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"total = %@",responseObject[@"total"]);
        self.totalNumber = responseObject[@"total"];
        NSArray *resultArr = responseObject[@"result"];
        for (NSMutableDictionary *channelDic in resultArr) {
            [self.channelArr addObject:channelDic[@"channel"]];
        }
        NSMutableArray *arrayM = [VideoModel mj_objectArrayWithKeyValuesArray:self.channelArr];

            if (type == 1) {
                self.sourcrArray = arrayM;
                [s.collectionView.mj_header endRefreshing];
            }else if (type == 2){
                [self.sourcrArray removeAllObjects];
                [self.sourcrArray addObjectsFromArray:arrayM];
//                self.sourcrArray = arrayM;
                NSLog(@"数组 =%ld",self.sourcrArray.count);
                [s.collectionView.mj_footer endRefreshing];
            }
            [s.collectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }] resume];
    NSLog(@"+++++%ld",self.sourcrArray.count);
}


#pragma mark --- collection代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.sourcrArray.count;
    
}



//返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    VideoModel *model = self.sourcrArray[indexPath.item];
    cell.videoModel = model;
    return cell;
}
//跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    VideoDetailController *detailVC = [[VideoDetailController alloc] init];
    VideoModel *videoModel = self.sourcrArray[indexPath.item];
    detailVC.videoModel = videoModel;
    [self.navigationController pushViewController:detailVC animated:YES];
    
    
    
}

#pragma mark ---WaterFlowLayout代理
- (CGFloat)waterflowLayout:(WaterflowLayout *)waterflowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath{
    VideoModel *model = self.sourcrArray[indexPath.item];
//    NSLog(@"%lf",model.width.floatValue);
//    CGFloat val = width / model.width.floatValue * model.height.floatValue;
//    NSLog(@"IndexPath == %lf",val);
    return width / model.width.floatValue * model.height.floatValue;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
